<script setup>
import * as Api from "@req/api";
import { suc } from "@/utils";
import { Modal, message } from "ant-design-vue";
import { ref, onMounted, defineProps, watch, shallowRef, nextTick, defineEmits } from "vue";

const emit = defineEmits(['close']);
const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  selectId: {
    type: String,
    default: () => { }
  }
});

onMounted(() => {
  getProdList()
})


const prodList = ref([]);
const selectNow = ref(null);

const pgData = ref({
  page: 1,
  per_page: 10,
  total: 1
})

const pageChange = () => {
  getProdList()
}

const getProdList = () => {
  Api.getProductList(pgData.value).then((res) => {
    if (suc(res.status)) {
      pgData.value.total = res.data.pagination.total_products;
      prodList.value = res.data.data;
      if (props.selectId) {
        selectNow.value = props.selectId;
      }
    }
  });
}


const queryPd = (id) => {
  Api.queryProduct(id).then((res) => {
    if (suc(res.status)) {
      emit('close', { type: true, data: res.data })
    }
  })
}

const onClose = () => {
  emit('close', { type: false })
};

const onSubmit = () => {
  queryPd(selectNow.value)
};

const selectFun = (id) => {
  selectNow.value = id;
}

watch(() => props.open, (val) => {
  if (val) {
    getProdList()
  }
})

</script>

<template>
  <a-modal v-model:open="props.open" width="900px" title="选择产品" @cancel="onClose" :maskClosable="false">
    <div class="no-list" v-if="prodList.length === 0">
      暂无产品
    </div>
    <div v-else>
      <div class="prod-list">
        <div :class="['prod-item', { active: selectNow === item.id }]" v-for="(item, index) in prodList" :key="index"
          @click="selectFun(item.id)">
          <img :src="item.img" alt="">
          <span>{{ item.name }}</span>
        </div>
      </div>
    </div>
    <a-pagination class="pagination" v-model:current="pgData.page" :total="pgData.total" :pageSize="pgData.per_page"
      @change="pageChange" show-less-items />
    <template #footer>
      <a-button style="margin-right: 8px" @click="onClose(false)">Cancel</a-button>
      <a-button type="primary" @click="onSubmit" :disabled="!selectNow || prodList.length == 0">Submit</a-button>
    </template>
  </a-modal>
</template>


<style scoped lang="postcss">
.no-list {
  display: flex;
  justify-content: center;
  padding: 50px 0;
}

.prod-list {
  display: flex;
  flex-wrap: wrap;

  .prod-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    border-radius: 10px;
    cursor: pointer;
    border: 1px solid transparent;
    width: 170px;
    padding: 10px;

    &.active {
      border-color: #67C5CB;
    }

    img {
      width: 150px;
      height: 150px;
      border-radius: 10px;
    }

    span {
      padding: 10px;
    }
  }
}
</style>